/**
 * Export Task React Query Hooks
 * 数据字典导出钩子 (FR-013 ~ FR-015)
 */

import { useQuery, useMutation, useQueryClient, UseQueryResult } from '@tanstack/react-query'
import { message } from 'antd'
import * as exportApi from '@/services/api/export'
import type { PageResponse, ExportTask, ExportTaskCreateRequest } from '@/services/models/types'
import { ExportStatus } from '@/services/models/types'

// Query Keys for export operations
export const exportQueryKeys = {
  all: ['exportTasks'] as const,
  lists: () => [...exportQueryKeys.all, 'list'] as const,
  list: (filters: Record<string, any>) => [...exportQueryKeys.lists(), filters] as const,
  details: () => [...exportQueryKeys.all, 'detail'] as const,
  detail: (id: number) => [...exportQueryKeys.details(), id] as const,
}

// ============================================
// Query Hooks - 查询钩子
// ============================================

/**
 * 导出任务列表查询 (FR-013)
 */
export const useExportTaskList = (params: any, options?: any): UseQueryResult<ExportTask[]> => {
  return useQuery<ExportTask[]>({
    queryKey: exportQueryKeys.list(params),
    queryFn: async () => {
      const response = await exportApi.listExportTasks(params)
      if (!response.success) throw new Error(response.message)

      // 后端返回 List<ExportResponse>,不是 PageResponse
      const data = response.data as any
      if (Array.isArray(data)) {
        return data
      }
      if (data && data.content && Array.isArray(data.content)) {
        return data.content
      }
      return []
    },
    staleTime: 30000, // 30s
    ...options,
  })
}

// ============================================
// Mutation Hooks - 变更钩子
// ============================================

/**
 * 创建导出任务 (FR-014)
 */
export const useCreateExportTask = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (data: ExportTaskCreateRequest) => {
      const response = await exportApi.createExportTask(data)
      if (!response.success) throw new Error(response.message)
      return response.data!
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: exportQueryKeys.lists() })
      message.success(`导出任务已创建,正在生成${data.format.toUpperCase()}文件...`)
    },
    onError: (error: Error) => {
      message.error(`创建导出任务失败: ${error.message}`)
    },
  })
}

/**
 * 下载导出文件 (FR-015)
 * 返回Blob对象供前端触发下载
 */
export const useDownloadExportFile = () => {
  return useMutation({
    mutationFn: async (id: number) => {
      return await exportApi.downloadExportFile(id)
    },
    onSuccess: (blob, id) => {
      // 创建下载链接并触发下载
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `metadata_export_${id}_${Date.now()}.xlsx` // 默认文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)

      message.success('文件下载已开始')
    },
    onError: (error: Error) => {
      message.error(`文件下载失败: ${error.message}`)
    },
  })
}

/**
 * 重试归档 (错误处理)
 */
export const useRetryArchive = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (id: number) => {
      const response = await exportApi.retryArchive(id)
      if (!response.success) throw new Error(response.message)
      return id
    },
    onSuccess: (id) => {
      queryClient.invalidateQueries({ queryKey: exportQueryKeys.lists() })
      queryClient.invalidateQueries({ queryKey: exportQueryKeys.detail(id) })
      message.success('正在重试归档...')
    },
    onError: (error: Error) => {
      message.error(`重试归档失败: ${error.message}`)
    },
  })
}

/**
 * 轮询导出任务状态
 * 当任务状态为RUNNING时,每3秒自动刷新
 */
export const useExportTaskPolling = (id: number, enabled: boolean = true) => {
  return useQuery({
    queryKey: [...exportQueryKeys.detail(id), 'polling'],
    queryFn: async () => {
      const response = await exportApi.listExportTasks({ id })
      if (!response.success) throw new Error(response.message)

      // 后端返回 List<ExportResponse>
      const tasks = response.data as any
      if (Array.isArray(tasks) && tasks.length > 0) {
        return tasks[0]
      }
      if (tasks?.content && Array.isArray(tasks.content) && tasks.content.length > 0) {
        return tasks.content[0]
      }
      throw new Error('导出任务不存在')
    },
    enabled: enabled && !!id,
    refetchInterval: (query) => {
      // Poll if task is still running
      if (query.state.data && (query.state.data.status === ExportStatus.RUNNING || query.state.data.status === ExportStatus.PENDING)) {
        return 3000 // 3 seconds
      }
      return false // Stop polling when completed/failed
    },
    staleTime: 0,
  })
}

// ============================================
// Utility Hooks - 工具钩子
// ============================================

/**
 * 快速导出钩子
 * 创建导出任务 + 自动轮询 + 完成后下载
 */
export const useQuickExport = () => {
  const createMutation = useCreateExportTask()
  const downloadMutation = useDownloadExportFile()

  return {
    /**
     * 执行快速导出
     * @param data 导出请求数据
     * @param autoDownload 是否在完成后自动下载(默认true)
     */
    execute: async (data: ExportTaskCreateRequest, autoDownload = true) => {
      const task = await createMutation.mutateAsync(data)

      // 轮询任务状态,直到完成或失败
      const checkStatus = async (): Promise<ExportTask> => {
        const response = await exportApi.listExportTasks({ id: task.id })
        if (!response.success) throw new Error(response.message)

        // 后端返回 List<ExportResponse>
        const tasks = response.data as any
        let currentTask: ExportTask | undefined
        if (Array.isArray(tasks) && tasks.length > 0) {
          currentTask = tasks[0]
        } else if (tasks?.content && Array.isArray(tasks.content) && tasks.content.length > 0) {
          currentTask = tasks.content[0]
        }

        if (!currentTask) throw new Error('任务不存在')

        if (currentTask.status === ExportStatus.SUCCESS) {
          return currentTask
        } else if (currentTask.status === ExportStatus.FAILED) {
          throw new Error(currentTask.errorMessage || '导出失败')
        } else {
          // Still running, wait and retry
          await new Promise(resolve => setTimeout(resolve, 3000))
          return checkStatus()
        }
      }

      const completedTask = await checkStatus()

      if (autoDownload) {
        await downloadMutation.mutateAsync(completedTask.id)
      }

      return completedTask
    },
    isLoading: createMutation.isPending || downloadMutation.isPending,
    error: createMutation.error || downloadMutation.error,
  }
}
